<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { getUserEnrollActivityAPI } from '@/services/activity'
import type { ActivityUserVo } from '@/types/activity'

// 定义组件属性
const props = defineProps({
  // 活动完成状态（0-未完成,1-已完成）
  finish: {
    type: Number,
    default: 0,
  },
})

// 定义子组件事件
const emit = defineEmits(['update:loading'])

// 数据状态
const state = reactive({
  list: [] as ActivityUserVo[],
  loading: false,
  hasMore: true,
  currentPage: 1,
  pageSize: 5,
})

// 向父组件暴露方法
defineExpose({
  loadData,
  loadMoreData,
  refreshData,
  getCurrentData: () => state.list,
})

// 监听状态变化，重新加载数据
watch(
  () => props.finish,
  () => {
    // 重置状态并加载数据
    state.list = []
    state.currentPage = 1
    state.hasMore = true
    loadData()
  },
)

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})

// 加载数据
async function loadData() {
  if (state.loading) return

  state.loading = true
  emit('update:loading', true)

  try {
    const res = await getUserEnrollActivityAPI({
      finish: props.finish,
      pageNum: state.currentPage,
      pageSize: state.pageSize,
    })

    if (res.code === 200) {
      state.list.push(...res.rows)
      state.hasMore = state.list.length < res.total && res.total > 0
    }
  } catch (error) {
    console.error('加载活动数据失败', error)
  } finally {
    state.loading = false
    emit('update:loading', false)
  }
}

// 加载更多数据
async function loadMoreData() {
  if (!state.hasMore || state.loading) return

  state.loading = true
  state.currentPage++
  emit('update:loading', true)

  try {
    const res = await getUserEnrollActivityAPI({
      finish: props.finish,
      pageNum: state.currentPage,
      pageSize: state.pageSize,
    })

    if (res.code === 200) {
      const newRows = res.rows || []
      if (newRows.length > 0) {
        state.list = [...state.list, ...newRows]
        state.hasMore = newRows.length >= state.pageSize
      } else {
        state.hasMore = false
      }
    }
  } catch (error) {
    console.error('加载更多活动数据失败', error)
  } finally {
    state.loading = false
    emit('update:loading', false)
  }
}

// 刷新数据
async function refreshData() {
  state.currentPage = 1
  state.loading = true
  emit('update:loading', true)

  try {
    const res = await getUserEnrollActivityAPI({
      finish: props.finish,
      pageNum: state.currentPage,
      pageSize: state.pageSize,
    })

    if (res.code === 200) {
      state.list = res.rows || []
      state.hasMore = (res.rows?.length || 0) >= state.pageSize
    }
  } catch (error) {
    console.error('刷新活动数据失败', error)
  } finally {
    state.loading = false
    emit('update:loading', false)
  }
}

// 格式化日期
const formatDate = (date: Date | string | undefined) => {
  if (!date) return '未知时间'
  if (typeof date === 'string') {
    date = new Date(date)
  }
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(
    date.getDate(),
  ).padStart(2, '0')}`
}

// 跳转到活动详情页
const goToActivityDetail = (activityId: number | undefined) => {
  if (!activityId) return
  uni.navigateTo({
    url: `/pagesActivity/activity-detail/activity-detail?id=${activityId}`,
  })
}

// 获取活动状态文本和样式
const getActivityStatus = (status: number | undefined) => {
  if (status === undefined) return { text: '未知', class: 'status-unknown' }

  const statusMap: Record<number, { text: string; class: string }> = {
    1: { text: '报名中', class: 'status-not-started' },
    2: { text: '进行中', class: 'status-ongoing' },
    3: { text: '已结束', class: 'status-ended' },
    4: { text: '已取消', class: 'status-canceled' },
  }

  return statusMap[status] || { text: '未知', class: 'status-unknown' }
}
</script>

<template>
  <view class="activity-list">
    <!-- 空态展示 -->
    <view class="empty-state" v-if="state.list.length === 0 && !state.loading">
      <image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image>
      <text class="empty-text">暂无活动信息</text>
    </view>

    <!-- 活动列表 -->
    <view class="activity-items" v-else>
      <view
        class="activity-item"
        v-for="(item, index) in state.list"
        :key="index"
        @tap="goToActivityDetail(item.activityId)"
      >
        <image
          class="activity-image"
          :src="item.activity?.coverImage || '/static/images/empty.png'"
          mode="aspectFill"
        >
        </image>
        <view class="activity-content">
          <view class="activity-title">{{ item.activity?.title || '未知活动' }}</view>
          <view class="activity-detail">
            <view class="activity-time">
              <text class="detail-label">时间：</text>
              {{ formatDate(item.activity?.startTime) }} - {{ formatDate(item.activity?.endTime) }}
            </view>
            <view class="activity-location" v-if="item.activity?.location">
              <text class="detail-label">地点：</text>
              {{ item.activity.location }}
            </view>
          </view>
          <view class="activity-info">
            <view
              class="activity-completion"
              :class="props.finish === 1 ? 'status-completed' : 'status-ongoing'"
            >
              {{ props.finish === 1 ? '已完成' : '未完成' }}
            </view>
            <view class="activity-status" :class="getActivityStatus(item.activity?.status).class">
              {{ getActivityStatus(item.activity?.status).text }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多状态 -->
    <view class="load-more" v-if="state.list.length > 0">
      <text v-if="state.hasMore && !state.loading">上拉加载更多</text>
      <text v-if="state.loading">加载中...</text>
      <text v-if="!state.hasMore && !state.loading">没有更多了</text>
    </view>
  </view>
</template>

<style lang="scss">
.activity-list {
  width: 100%;
  padding-bottom: 30rpx;

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;

    .empty-image {
      width: 240rpx;
      height: 240rpx;
      margin-bottom: 20rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }

  .activity-items {
    width: 100%;

    .activity-item {
      display: flex;
      background-color: #fff;
      border-radius: 12rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

      .activity-image {
        width: 180rpx;
        height: 180rpx;
        border-radius: 8rpx;
        background-color: #f5f5f5;
        margin-right: 20rpx;
      }

      .activity-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .activity-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .activity-detail {
          display: flex;
          flex-direction: column;
          margin-bottom: 10rpx;

          .activity-time,
          .activity-location {
            font-size: 24rpx;
            color: #666;
            margin-bottom: 4rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .detail-label {
            color: #999;
          }
        }

        .activity-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: auto;

          .activity-completion,
          .activity-status {
            font-size: 24rpx;
            padding: 4rpx 12rpx;
            border-radius: 20rpx;
          }

          .activity-completion {
            &.status-ongoing {
              color: #4a69bd;
              background-color: rgba(74, 105, 189, 0.1);
            }

            &.status-completed {
              color: #2ecc71;
              background-color: rgba(46, 204, 113, 0.1);
            }
          }

          .activity-status {
            margin-left: 10rpx;

            &.status-not-started {
              color: #1296db;
              background-color: rgba(18, 150, 219, 0.1);
            }

            &.status-ongoing {
              color: #07c160;
              background-color: rgba(7, 193, 96, 0.1);
            }

            &.status-ended {
              color: #8a8a8a;
              background-color: rgba(138, 138, 138, 0.1);
            }

            &.status-canceled {
              color: #ff4d4f;
              background-color: rgba(255, 77, 79, 0.1);
            }

            &.status-unknown {
              color: #999;
              background-color: rgba(153, 153, 153, 0.1);
            }
          }
        }
      }
    }
  }

  .load-more {
    text-align: center;
    padding: 20rpx 0;
    font-size: 24rpx;
    color: #999;
  }
}
</style>
